<template>
  <a-select
    v-model:value="unitIds"
    :mode="initMode"
    show-search
    :class="{'m-r-5': showLength > 1 || !props.noSpace}"
    :filter-option="filterOption"
    :max-tag-count="1"
    :placeholder="getPlaceholder(0, '请选择单位名称')"
    :options="unitOptions"
    @change="(val) => handleUnitChange(val)"
  />
  <a-select
    v-if="showLength > 1"
    v-model:value="storeAreaIds"
    :mode="initMode"
    show-search
    :class="{'m-r-5': showLength > 2 || !props.noSpace}"
    :filter-option="filterOption"
    :max-tag-count="1"
    :placeholder="getPlaceholder(1, '请选择库区名称')"
    :options="storeAreaOptions"
    @change="(val) => handleAreaChange(val)"
  />
  <a-select
    v-if="showLength > 2"
    v-model:value="warehouseIds"
    :mode="initMode"
    show-search
    :class="{'m-r-5': showLength > 3 || !props.noSpace}"
    :filter-option="filterOption"
    :max-tag-count="1"
    :placeholder="getPlaceholder(2, '请选择仓房名称')"
    :options="warehouseOptions"
    @change="(val) => handleWarehouseChange(val)"
  />
  <a-select
    v-if="showLength > 3"
    v-model:value="goodsSiteIds"
    :mode="initMode"
    show-search
    :class="{'m-r-5': !props.noSpace}"
    :filter-option="filterOption"
    :max-tag-count="1"
    placeholder="请选择货位名称"
    :options="goodsSiteOptions"
    @change="() => handleGoodsSiteChange()"
  />
</template>

<!--组件自定义-单位下拉选择-->
<script setup lang="ts">
import { useRoute } from 'vue-router'
import { computed, onMounted, ref, watch } from 'vue'
import api from '../api'

type IdType = any
type OptionType = {
  value: string | number
  label: string
}

interface MFacilityCascadeProps {
  showLength?: number
  noSpace?: boolean
  selectFirst?: boolean
  mode?: string
  initUnitIds?: IdType
  initStoreAreaIds?: IdType
  initWarehouseIds?: IdType
  initGoodsSiteIds?: IdType
  placeholderList?: string[]
}

const props = withDefaults(defineProps<MFacilityCascadeProps>(), {
  // 控制select是否展示，默认全部展示
  showLength: 4,
  // 控制是否需要margin-right: 5的样式,true为不需要，默认需要
  noSpace: false,
  selectFirst: false,
  mode: 'multiple',
})

// 监听变化
watch(
  () => [props.initUnitIds, props.initStoreAreaIds, props.initWarehouseIds, props.initGoodsSiteIds],
  (newVal, oldVal) => {
    console.log("watch initIds")
    initIds()
  }
)

const emit = defineEmits(['change'])
const route = useRoute()

//单位
let unitOptions = ref<OptionType[]>([])
//库区
let storeAreaOptions = ref<OptionType[]>([])
//仓房
let warehouseOptions = ref<OptionType[]>([])
//货位
let goodsSiteOptions = ref<OptionType[]>([])

//单位ids集合
let unitIds = ref<IdType>()
//库区ids集合
let storeAreaIds = ref<IdType>()
//	仓房ids
let warehouseIds = ref<IdType>()
//货位ids集合
let goodsSiteIds = ref<IdType>()

const selectFlag = ref<boolean>(false)

const initSelectFirst = computed(() => props.selectFirst)

const initMode = computed(() => props.mode)

const isMultiple = initMode.value == 'multiple'

onMounted(() => {
  initIds()
  selectFlag.value = initSelectFirst.value
  getUnitList()
})

const getPlaceholder = (index: number, commonText: string): string => {
  return props?.placeholderList?.[index] || commonText
}

const initIds = (): void => {
  const getValue = (value): IdType => isMultiple ? value : value[0]

  if (props.initUnitIds) {
    unitIds.value = props.initUnitIds
  }
  unitIds.value = getValue(unitIds.value)
  if (props.initStoreAreaIds) {
    storeAreaIds.value = props.initStoreAreaIds
  }
  storeAreaIds.value = getValue(storeAreaIds.value)
  if (props.initWarehouseIds) {
    warehouseIds.value = props.initWarehouseIds
  }
  warehouseIds.value = getValue(warehouseIds.value)
  if (props.initGoodsSiteIds) {
    goodsSiteIds.value = props.initGoodsSiteIds
  } else {
    goodsSiteIds.value = []
  }
  goodsSiteIds.value = getValue(goodsSiteIds.value)
}

function getUnitList(): void {
  //查询单位
  api.facilityLink(0).then((resp) => {
    const list = resp.data.data
    list.forEach(item => {
      unitOptions.value.push({ value: item.ssid, label: item.ssmc })
    })
    // 只有一个单位时，默认选中
    if (unitOptions.value.length === 1 || selectFlag.value) {
      const value = unitOptions.value[0].value
      unitIds.value = isMultiple ? [value] : value
      handleUnitChange(unitIds.value)
      return
    }

    // 初始化的时候
    const queryFlag = isNeedQuery(unitIds.value)
    if (queryFlag) {
      handleUnitChange(unitIds.value, true)
      return
    }
  })
}

//改变单位
const handleUnitChange = (value, init = false): void => {
  storeAreaOptions.value = []
  warehouseOptions.value = []
  goodsSiteOptions.value = []
  const val = toArray(value)
  if (!init) {
    storeAreaIds.value = undefined
    warehouseIds.value = undefined
    goodsSiteIds.value = undefined
  }

  // 查询库区
  api.facilityLink(1, val).then((resp) => {
    const list = resp.data.data
    list.forEach(item => {
      item.value = item.ssid
      item.label = item.ssmc
    })
    storeAreaOptions.value = val.length ? list : [] // 没有单位时清空查询内容
    warehouseOptions.value = []
    goodsSiteOptions.value = []

    // 只有一个库区时，默认选中
    if ((storeAreaOptions.value.length === 1 && unitIds.value) || selectFlag.value) {
      const value = storeAreaOptions.value[0].value
      storeAreaIds.value = isMultiple ? [value] : value
      handleAreaChange(storeAreaIds.value, init)
      return
    }
    // 初始化的时候

    if (init && storeAreaIds.value && storeAreaIds.value?.length > 0) {
      handleAreaChange(storeAreaIds.value, true)
      return
    }
    if (!init) {
      emitChange()
    }
  })
}

//改变库区
const handleAreaChange = (value, init = false): void => {
  warehouseOptions.value = []
  goodsSiteOptions.value = []
  const val = toArray(value)
  if (!init) {
    warehouseIds.value = undefined
    goodsSiteIds.value = undefined
  }

  // 查询仓房
  api.facilityLink(2, val).then((resp) => {
    const list = resp.data.data
    list.forEach(item => {
      item.value = item.ssid
      item.label = item.ssmc
    })
    warehouseOptions.value = val.length ? list : [] // 没有单位时清空查询内容
    goodsSiteOptions.value = []

    // 只有一个仓房时，默认选中
    if ((warehouseOptions.value.length === 1 && storeAreaIds.value) || selectFlag.value) {
      const value = warehouseOptions.value[0].value
      warehouseIds.value = isMultiple ? [value] : value
      handleWarehouseChange(warehouseIds.value, init)
      return
    }
    // 初始化的时候
    if (init && warehouseIds.value && warehouseIds.value?.length > 0) {
      handleWarehouseChange(warehouseIds.value, true)
      return
    }
    if (!init) {
      emitChange()
    }
  })
}
//改变仓房
const handleWarehouseChange = (value, init = false): void => {
  goodsSiteOptions.value = []
  const val = toArray(value)
  if (!init) {
    goodsSiteIds.value = undefined
  }

  // 查询货位
  api.facilityLink(3, val).then((resp) => {
    const list = resp.data.data
    list.forEach(item => {
      item.value = item.ssid
      item.label = item.ssmc
    })
    goodsSiteOptions.value = val.length ? list : [] // 没有单位时清空查询内容

    // 只有一个货位时，默认选中
    if (goodsSiteOptions.value.length === 1 || selectFlag.value) {
      const value = goodsSiteOptions.value[0].value
      goodsSiteIds.value = isMultiple ? [value] : value
      handleGoodsSiteChange()
    }
    if (!init) {
      emitChange()
    }
    selectFlag.value = false
  })
}
//改变货位
const handleGoodsSiteChange = (init = false): void => {
  if (!init) {
    emitChange()
  }
}
const filterOption = (input: string, option: OptionType):boolean => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

function reset(): void {
  unitIds.value = undefined
  storeAreaIds.value = undefined
  warehouseIds.value = undefined
  goodsSiteIds.value = undefined
  storeAreaOptions.value = []
  warehouseOptions.value = []
  goodsSiteOptions.value = []
  emitChange()
}

function emitChange(): void {
  emit('change', {
    unitIds: toArray(unitIds.value),
    storeAreaIds: toArray(storeAreaIds.value),
    warehouseIds: toArray(warehouseIds.value),
    goodsSiteIds: toArray(goodsSiteIds.value),
    storeAreaOptions,
    warehouseOptions,
  })
}

const isArray = Array.isArray

const toArray = (value: unknown): number[] => (isArray(value) ? value : value === undefined ? []: [value]) as number[]

const isNeedQuery = (value: unknown): boolean =>
  !!((isArray(value) && value.length) || (!isArray(value) && value))

defineExpose({ initIds, reset })
</script>

<style scoped lang="less">
.ant-select {
  width: 160px;
  height: 32px;
  font-size: 12px;

  .ant-select-selector {
    height: 32px;
  }
}

:deep(.ant-select-selection-item) {
  max-width: 80px;
}
</style>
